package com.visionet.school.app.web.wechat.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class DataTransfer {
	private static final Logger log = LoggerFactory
			.getLogger(DataTransfer.class);
	/**
     * 上传媒体文件到微信
     * 
     * @param url
     *            提交的网址
     * @param params
     *            提交的参数
     * @return 返回的结果
	 * @throws  Exception
     */
	public static String PostDataToWeiXin(String strURL,String params) {        
        return PostDataToWeiXin(strURL,params,false);
	}
	/**
     * 上传媒体文件到微信
     * 
     * @param url
     *            提交的网址
     * @param params
     *            提交的参数
     * @return 返回的结果
	 * @throws  Exception
     */
	public static String PostDataToWeiXin(String strURL,String params,boolean appendBR) {
		String resString="";
		// 请求方式
        if(params!=null && params!="")
		{
        	resString=PostDataToWeiXin(strURL,params,"POST",appendBR);
		}else {
			resString=PostDataToWeiXin(strURL,params,"GET",appendBR);
		}
        
        return resString;
	}
	/**
     * 上传内容到微信
     * 
     * @param url
     *            提交的网址
     * @param method
     *            提交方式
     * @param params
     *            提交的参数
     * @return 返回的结果
	 * @throws  Exception
     */
	public static String PostDataToWeiXin(String strURL,String params,String method,boolean appendBR) {
		StringBuffer bufferRes = new StringBuffer();
        String resString="";
        try {
	        	URL realUrl=new URL(strURL);
	    		
	            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
                // 连接超时

                conn.setConnectTimeout(25000);

                // 读取超时 --服务器响应比较慢,增大时间

                conn.setReadTimeout(25000);

                HttpURLConnection.setFollowRedirects(true);

                // 请求方式
                conn.setRequestMethod(method);
                
                conn.setDoOutput(true);

                conn.setDoInput(true);

                conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");

                conn.setRequestProperty("Referer", "https://api.weixin.qq.com/");
                conn.setRequestProperty("Charset", "UTF-8"); 
                conn.connect();

                // 获取URLConnection对象对应的输出流
				if(params!=null && params!="")
				{
					//System.out.println(params);
	                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
	
	                // 发送请求参数
	
	                //out.write(URLEncoder.encode(params,"UTF-8"));
	
	                out.write(params);
	
	                out.flush();
	
	                out.close();
				}
                InputStream in = conn.getInputStream();

                BufferedReader read = new BufferedReader(new InputStreamReader(in,"UTF-8"));

                String valueString = null;

                while ((valueString=read.readLine())!=null){

                        bufferRes.append(valueString);
                        if(appendBR){
                        	bufferRes.append("\r\n");
                        }
                }
                resString=bufferRes.toString();
                log.info(resString);

                in.close();
                if (conn != null) {
                    // 关闭连接
                    conn.disconnect();
                 }
        	
                return resString;

        } catch (Exception e) {

                e.printStackTrace();
                resString=e.getMessage();
        }
        finally{
           
        }
        
        return resString;
	}
	/**
     * 上传媒体文件到微信
     * 
     * @param url
     *            提交的网址
     * @param file
     *            提交的文件
     * @return 返回的结果
	 * @throws  Exception
     */
    public static String PostFileToWeiXin(String url, String filePath) {
    	String result = null;  
    	try {
    		File file = new File(filePath);  
	        if (!file.exists() || !file.isFile()) {  
	        	return "404";
	        }  
	      
	        /** 
	        * 第一部分 
	        */  
	        URL urlObj = new URL(url);  
	        // 连接  
	        HttpURLConnection con = (HttpURLConnection)urlObj.openConnection();
	        /** 
	        * 设置关键值 
	        */  
	        con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式  
	        con.setDoInput(true);  
	        con.setDoOutput(true);  
	        con.setUseCaches(false); // post方式不能使用缓存        
	      
	        // 设置请求头信息  
	        con.setRequestProperty("Connection", "Keep-Alive");  
	        con.setRequestProperty("Charset", "UTF-8");        
	      
	        // 设置边界  
	        String BOUNDARY = "----------" + System.currentTimeMillis();  
	        con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY); 
	      
	        // 请求正文信息 
	      
	        // 第一部分：  
	        StringBuilder sb = new StringBuilder();  
	        sb.append("--"); // 必须多两道线  
	        sb.append(BOUNDARY);  
	        sb.append("\r\n");  
	        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""  
	        + file.getName() + "\"\r\n");  
	        sb.append("Content-Type:application/octet-stream\r\n\r\n"); 
	        
	        byte[] head = sb.toString().getBytes("utf-8");
	      
	        // 获得输出流  
	        OutputStream out = new DataOutputStream(con.getOutputStream());  
	        // 输出表头  
	        out.write(head);  
	      
	        // 文件正文部分  
	        // 把文件已流文件的方式 推入到url中  
	        DataInputStream in = new DataInputStream(new FileInputStream(file));  
	        int bytes = 0;  
	        byte[] bufferOut = new byte[1024];  
	        while ((bytes = in.read(bufferOut)) != -1) {  
	        	out.write(bufferOut, 0, bytes);  
	        }  
	        in.close();
	      
	        // 结尾部分  
	        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
	      
	        out.write(foot);  
	      
	        out.flush();  
	        out.close();
	      
	        StringBuffer buffer = new StringBuffer();  
	        BufferedReader reader = null;  
          
	        // 定义BufferedReader输入流来读取URL的响应  
	        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
	        String line = null;  
	        while ((line = reader.readLine()) != null) { 
	        	buffer.append(line);  
	        }  
	        if(result==null){  
	        	result = buffer.toString();  
	        }  
	        if(reader!=null){  
	        	reader.close();  
	        }
        } catch (IOException e) {  
	        log.info("发送POST请求出现异常！" + e);  
	        return "504";  
        } finally {  
	        
        }
      
        JSONObject jsonObj = JSONObject.parseObject(result);  
        String mediaId = jsonObj.getString("media_id");  
        return mediaId;
    }
    /*
     * 输出字符
     */
    public static void outputResponseString(HttpServletResponse response,String datastr){
	    OutputStream outputStream;
		try {
			//获取OutputStream输出流
			outputStream = response.getOutputStream();
			response.setHeader("content-type", "text/html;charset=UTF-8");//通过设置响应头控制浏览器以UTF-8的编码显示数据，如果不加这句话，那么浏览器显示的将是乱码
		    byte[] dataByteArr = datastr.getBytes("UTF-8");//将字符转换成字节数组，指定以UTF-8编码进行转换
		    outputStream.write(dataByteArr);//使用OutputStream流向客户端输出字节数组
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			//e.printStackTrace();
		}
   }
}
